﻿using System;
using System.Net;
using System.Threading;
using Selenium;

namespace IntegrationTests.Core.Websites
{
	public class TimeoutHttpCommandProcessor : HttpCommandProcessor
	{
		public TimeoutHttpCommandProcessor(string serverHost, int serverPort, string browserStartCommand, string browserURL)
			: base(serverHost, serverPort, browserStartCommand, browserURL)
		{
		}

		public TimeoutHttpCommandProcessor(string serverURL, string browserStartCommand, string browserURL)
			: base(serverURL, browserStartCommand, browserURL)
		{
		}

		private static void TimeOut(Action action, int timeoutMsec = 30000)
		{
			Thread threadToKill = null;
			Exception exception = null;

			Action wrappedAction = () =>
			                       	{
			                       		threadToKill = Thread.CurrentThread;
			                       		try
			                       		{
			                       			action();
			                       		}
			                       		catch (Exception e)
			                       		{
			                       			exception = e;
			                       		}
			                       	};
			IAsyncResult result = wrappedAction.BeginInvoke(null, null);
			if (result.AsyncWaitHandle.WaitOne(timeoutMsec))
			{
				wrappedAction.EndInvoke(result);
			}
			else
			{
				threadToKill.Abort();
				exception = new TimeoutException();
			}
			if (exception != null)
				throw exception;
		}

		public override WebRequest CreateWebRequest(IRemoteCommand command)
		{
			WebRequest request = base.CreateWebRequest(command);
			request.Timeout = 60000;
			return request;
		}
	}
}